package com.hj.hos.service;

import cn.hutool.core.text.CharPool;
import com.hj.hos.HosService;
import com.hj.hos.properties.HosProperties;
import org.springframework.util.FileCopyUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * @author hj
 * @Date 2023/4/29
 * @Description: 本地存储
 */
public class LocalHosService extends HosService {

    public LocalHosService(HosProperties properties) {
        this.properties = properties;
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }


    @Override
    public String upload(InputStream inputStream, String path) {

        try {
            File file = new File(properties.getLocal().getPath() + File.separator + path);
            // 没有目录，则自动创建目录
            File parent = file.getParentFile();
            if (null != parent && !parent.mkdirs() && !parent.isDirectory()) {
                throw new IOException("目录 '" + parent + "' 创建失败");
            }
            FileCopyUtils.copy(inputStream, Files.newOutputStream(file.toPath()));
        } catch (Exception e) {
            throw new RuntimeException("本地存储--上传文件失败：", e);
        }
        return properties.getConfig().getDomain() + CharPool.SLASH + properties.getLocal().getUrl() + CharPool.SLASH + path;
    }


}
